package com.adaxi.adc.common.utils;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * @author 涛哥
 * @date 2023/9/29
 */
public class MD5Util {
    /**
     * 盐
     */
    public static final String SALT_VALUE = "lanqiao";

    /**
     * 不加盐值32位小写
     */
    public static String md5Lower(String plainText) {
        String md5 = null;
        if (null != plainText && !"".equals(plainText)) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(plainText.getBytes("UTF-8"));
                md5 = new BigInteger(1, md.digest()).toString(16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return md5;
    }

    /**
     * 加盐值32位小写
     */
    public static String md5LowerSalt(String plainText) {
        String md5 = null;
        if (null != plainText && !"".equals(plainText) && null != SALT_VALUE && !"".equals(SALT_VALUE)) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(plainText.getBytes("UTF-8"));
                md.update(SALT_VALUE.getBytes("UTF-8"));
                md5 = new BigInteger(1, md.digest()).toString(16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return md5;
    }

    /**
     * 不加盐值32位大写
     */
    public static String md5Upper(String plainText) {
        String md5 = md5Lower(plainText);
        return null == md5 ? md5 : md5.toUpperCase();
    }

    /**
     * 加盐值32位大写
     */
    public static String md5UpperSalt(String plainText) {
        String md5 = md5LowerSalt(plainText);
        return null == md5 ? md5 : md5.toUpperCase();
    }

    /**
     * 不加盐值16位小写
     */
    public static String md5Lower16(String plainText) {
        String md5 = md5Lower(plainText);
        return null == md5 ? md5 : md5.substring(8, 24);
    }

    /**
     * 加盐值16位小写
     */
    public static String md5LowerSalt16(String plainText) {
        String md5 = md5LowerSalt16(plainText);
        return null == md5 ? md5 : md5.substring(8, 24);
    }

    /**
     * 不加盐值16位大写
     */
    public static String md5Upper16(String plainText) {
        String md5 = md5Lower16(plainText);
        return null == md5 ? md5 : md5.toUpperCase();
    }

    /**
     * 加盐值16位大写
     */
    public static String md5Upper16Salt(String plainText) {
        String md5 = md5UpperSalt(plainText);
        return null == md5 ? md5 : md5.toUpperCase();
    }
}
